//
//  UserShareController.m
//  HappyBaby
//
//  Created by 华哥 on 15/11/28.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "UserShareController.h"
#import "Define.h"
#import "UserShareModel.h"


#import <BmobSDK/Bmob.h>
#import <BmobSDK/BmobProFile.h>

@interface UserShareController () <UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextViewDelegate, UIAlertViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UITextField *titleTextField;
//@property (nonatomic, strong) UITextField *textField;

// 服务器请求下来的数据
@property (nonatomic, strong) NSMutableArray *userShareModelArray;
@property (nonatomic, strong) UIButton *issueButton;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UITextView *textView;

@end

static NSString *cellIndentifier = @"cell";
@implementation UserShareController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加键盘弹出的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    // 添加键盘回收的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardHidden:) name:UIKeyboardWillHideNotification object:nil];
    // 添加键盘Frame改变的通知 (切换键盘时, 也会触发键盘弹出的方法, 所以很少用);
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardChange:) name:UIKeyboardDidChangeFrameNotification object:nil];

//    self.userShareModelArray = [self userShareModelArrayFormServer];
    self.navigationController.navigationBar.translucent = NO;
    [self createView];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithTitle:@"发表" style:UIBarButtonItemStylePlain target:self action:@selector(barButtonAction)];
    self.navigationItem.rightBarButtonItem = barButton;
}

//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    return 1;
//}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    return 20;
//}

- (void)createView
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    float scaleY = kScreenHeight / 667;
    // 标题textField;
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 40, 50, 40)];
    titleLabel.text = @"标题:";
    titleLabel.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:titleLabel];
    self.titleTextField = [[UITextField alloc]initWithFrame:CGRectMake(80, 40, kScreenWidth - 100, 40)];
    self.titleTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.titleTextField.placeholder = @"输入一个标题";
    self.titleTextField.delegate = self;
    [self.view addSubview:_titleTextField];
    
    // 分享内容textField;
    UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 100, 50, 40)];
    contentLabel.text = @"内容:";
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(self.titleTextField.x  , 100, self.titleTextField.width ,200 * scaleY)];
    [self.view addSubview:contentLabel];
    self.textView.layer.borderWidth = 1;
    self.textView.layer.cornerRadius = 5;
    self.textView.layer.borderColor = [UIColor colorWithRed:218 / 255.0 green:218 / 255.0 blue:218 / 255.0 alpha:1].CGColor;
    
    self.textView.font = [UIFont systemFontOfSize:15];
    
    self.textView.delegate = self;
//    self.textView.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
//    self.textView.adjustsFontSizeToFitWidth = YES;
    
    self.textView.keyboardAppearance = UIKeyboardAppearanceDefault;
    
    [self.view addSubview:_textView];

    UIImageView *bottomImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    bottomImage.image = [UIImage imageNamed:@"iconfont-iconfonttupian"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bottonTapAction:)];
    [bottomImage addGestureRecognizer:tap];
    bottomImage.userInteractionEnabled = YES;
    
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, (kScreenHeight - 64 - 49 - 30), kScreenWidth, 30)];
    self.bottomView.backgroundColor = [UIColor colorWithRed:237 / 255.0 green:237 / 255.0 blue:237 / 255.0 alpha:1];
    [self.bottomView addSubview:bottomImage];
    [self.view addSubview:_bottomView];
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(125, kScreenHeight, 100, 100)];
    self.imageView.image = [UIImage imageNamed:@"iconfont-tianjiatupian"];
    self.imageView.userInteractionEnabled = YES;
    self.imageView.hidden = YES;
    UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewTapAction:)];
    [self.imageView addGestureRecognizer:imageTap];
    [self.view addSubview:_imageView];
}

#pragma mark --------------------------  上传数据 ----------------------------------
// 点击barButton上出数据
- (void)barButtonAction
{
    if (self.titleTextField.text.length == 0)
    {
        UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"标题不能为空" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alterView show];
        return;
    }
    //    点击发布上传到云端服务器;
    BmobObject *object = [BmobObject objectWithClassName:@"UserPublic"];
    BmobUser *user = [BmobUser getCurrentUser];
    
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.jpg",[self documentFolderPath], self.nowTime];
    NSLog(@"filePath ==== %@", filePath);
    
//    UIImage *headerImage = [user objectForKey:@"userHeaderImage"];
    [object setObject:user.username forKey:@"username"];
//    [object setObject:headerImage forKey:@"userHeadImage"];
    
    [object setObject:self.textView.text forKey:@"shareContent"];
    [object setObject:self.titleTextField.text forKey:@"userShareTitle"];
    if (self.imageView)
    {
        [BmobProFile uploadFileWithPath:filePath block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url, BmobFile *file) {
            if (isSuccessful) {
                NSLog(@"发布成功");
                [object setObject:file forKey:@"shareImage"];
                [object saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    if (isSuccessful) {
                        NSLog(@"发布成功");
                    }
                    else
                    {
                        NSLog(@"发布失败%@",error);
                    }
                }];
            }
            else
            {
                NSLog(@"%@",error);
            }
        } progress:^(CGFloat progress) {
            NSLog(@"%f",progress);
        }];
    }
    [object saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            NSLog(@"发布成功");
            UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"发布成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alterView show];
        }
        else
        {
            NSLog(@"发布失败%@",error);
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 点击图片 (跳出隐藏的View)
- (void)bottonTapAction:(UITapGestureRecognizer *)tap
{
    if (self.imageView.hidden)
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.bottomView.frame = CGRectMake(0, (kScreenHeight - 258 - 64  - 30), kScreenWidth, 30);
            self.imageView.y = 375;
            
        }completion:^(BOOL finished) {
            self.imageView.hidden = NO;
        }];
    }
    else
    {
        [UIView animateWithDuration:0.5 animations:^{
        self.bottomView.frame = CGRectMake(0, (kScreenHeight - 49 - 64 - 30), kScreenWidth, 30);
            self.imageView.y = 375;
            self.imageView.hidden = YES;
        }];
    }
}

#pragma mark ----------------- 键盘frame改变通知 -----------------------------
- (void)keyBoardShow:(NSNotification *)notification
{
    // 键盘弹出的时候相当于系统自己发出了一个 post 无需我们自己去调用;
    // 1. 得到键盘所有信息
    NSDictionary *info = [notification userInfo];
    // 2. 得到键盘弹出之后的 frame
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    // 3. 得到键盘的高度;
    CGSize size = [value CGRectValue].size;
    self.bottomView.frame = CGRectMake(0, (kScreenHeight - 64 - 30 - size.height), kScreenWidth, 30);
}

// 键盘frame改变执行的通知
- (void)keyBoardChange:(NSNotification *)notification
{
    // 1. 得到键盘所有信息
    NSDictionary *info = [notification userInfo];
    // 2. 得到键盘弹出之后的 frame
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    // 3. 得到键盘的高度;
    CGSize size = [value CGRectValue].size;
}

- (void)keyBoardHidden:(NSNotification *)nitification
{
    self.bottomView.frame = CGRectMake(0, (kScreenHeight - 64  - 30 - 49), kScreenWidth, 30);
    self.imageView.y = 700;
}

#pragma mark -------------------- 打开相册 ------------------------
// 点击图片添加照片;
- (void)imageViewTapAction:(UITapGestureRecognizer *)tap
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        //NSLog(@"打开相册成功");
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        //  是否允许编辑
        picker.allowsEditing = YES;
        //  设置代理，自动去调用代理方法
        //  需要遵守UINavigationControllerDelegate和UIImagePickerControllerDelegate协议
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        NSLog(@"打开相册失败");
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"ok");
    //  1.将选中的图片赋值给imageView
    //  通过字典的key值来取出对应的value值，value就是选中的图片
    UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //  将某一张图片存到相册中
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    CGSize imageSize = image.size;
    imageSize.height = 256;
    imageSize.width = 256;
    image = [self imageWithImage:image scaledToSize:imageSize];
    //给上传图片区域附上图片
    self.imageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    //获取时间来命名图片
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    self.nowTime = [NSString stringWithFormat:@"%f", a];
    NSLog(@"nowTime ==== %@", self.nowTime);
    [self saveImage:image WithName:[self.nowTime stringByAppendingString:@".jpg"]];
    
    //  2.将本界面模态回去，即dismiss
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 点击空白回收键盘;
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.textView resignFirstResponder];
    [self.titleTextField resignFirstResponder];
}
// 点击return回收键盘;
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
    return YES;
}

//压缩图片封装方法
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}

- (NSString *)documentFolderPath
{
    NSLog(@"documentFolderPath ==== %@",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}

/*
-(void)updataImage
{
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.jpg",[self documentFolderPath], self.nowTime];
    NSLog(@"filePath ==== %@", filePath);
    [BmobProFile uploadFileWithPath:filePath block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url,BmobFile *bmobFile) {
        if (isSuccessful) {
            //上传成功后返回文件名及url
            NSLog(@"filename:%@",filename);
            NSLog(@"url:%@",url);
            NSLog(@"bmobFile:%@\n",bmobFile);
            BmobObject *UserPush = [BmobObject objectWithClassName:@"UserPush"];
            [UserPush setObject:bmobFile forKey:@"photo"];
//            [UserPush setObject:self.issueView.textField.text forKey:@"info"];
            [UserPush saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if (isSuccessful)
                {
                    UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"上传成功"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alterView show];
                }
                else if(error)
                {
                    NSLog(@"error === %@", error);
                    UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"图片上传失败"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alterView show];
                }
            }];
        } else{
            if(error){
                NSLog(@"error%@",error);
                UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"图片上传失败"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alterView show];
            }
        }
    } progress:^(CGFloat progress) {
        //上传进度，此处可编写进度条逻辑
        NSLog(@"progress %f",progress);
    }];
}
*/


#pragma mark ------------------------- 加载上传数据 -------------------------------
// 获取到服务器数据返回到self.modelArray;
- (NSMutableArray *)userShareModelArrayFormServer
{
    NSMutableArray *objArray = [NSMutableArray array];
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"UserPublic"];
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        for (BmobObject *obj in array)
        {
            
            UserShareModel *userShareModel = [[UserShareModel alloc]init];
            // 两个用户信息;
            userShareModel.userInfoModel.username = [obj objectForKey:@"username"];
            userShareModel.userInfoModel.userHeadImage = [obj objectForKey:@"userHeaderImage"];
            userShareModel.shareContent = self.textView.text;
//            userShareModel.shareImage = self.imageView.image;
            [objArray addObject:userShareModel];
        }
    }];
    return objArray;
}























@end
